import {
  animationFrameScheduler,
  asapScheduler,
  asyncScheduler,
  Observable,
  observeOn,
  of,
  queueScheduler,
} from "rxjs";

export const otherSchedulerDemo = () => {
  const source$ = of(1, 2, 3, 4, 5);

  console.log("before");

  queueScheduler.schedule(() => {
    queueScheduler.schedule(() => console.log("second")); // will not happen now, but will be put on a queue
    console.log("first");
  });

  queueScheduler.schedule(() => console.log("three")); // will not happen now, but will be put on a queue

  // log: first, second ，three 放在队列中执行；

  // asapScheduler 安排在下一次事件队列中执行
  source$.pipe(observeOn(asyncScheduler)).subscribe((x) => {
    console.log(x, "i am async schedule");
  });

  // 这个会先执行，asapScheduler 会尽快安排当前事件事件队列中的任务先执行
  source$.pipe(observeOn(asapScheduler)).subscribe((x) => {
    console.log(x);
  });

  console.log("this is after");
};

export const animationFrameSchedulerDemo = () => {
  console.log("this is animaltionFrameSchduler demo");

  // 获取 DOM 元素
  const box = document.getElementById("box");
  let position = 0;

  // 创建基于 animationFrameScheduler 的 Observable
  const movementAnimation$ = new Observable((observer) => {
    const move = () => {
      position += 1;
      box!.style.left = position + "px";
      observer.next(position); // trigger subscribe;
      if (position < window.innerWidth - 50) {
        // 调度下次移动
        animationFrameScheduler.schedule(move);
      } else {
        observer.complete();
      }
    };

    // 启动动画
    animationFrameScheduler.schedule(move);
  });

  // 订阅 Observable
  movementAnimation$.subscribe({
    next: (position) => {
      console.log(position);
    },
    complete: () => console.log("Movement animation completed"),
  });
};
